import { CustomComponent, CUSTOM_COMPONENTS_KEY } from '../types';

/**
 * 获取所有自定义组件
 */
export function getCustomComponents(): CustomComponent[] {
  try {
    const data = localStorage.getItem(CUSTOM_COMPONENTS_KEY);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    console.error('获取自定义组件失败:', error);
    return [];
  }
}

/**
 * 保存所有自定义组件
 */
export function saveCustomComponents(components: CustomComponent[]): void {
  try {
    localStorage.setItem(CUSTOM_COMPONENTS_KEY, JSON.stringify(components));
  } catch (error) {
    console.error('保存自定义组件失败:', error);
  }
}

/**
 * 添加自定义组件
 */
export function addCustomComponent(component: CustomComponent): void {
  const components = getCustomComponents();
  components.push(component);
  saveCustomComponents(components);
}

/**
 * 删除自定义组件
 */
export function deleteCustomComponent(id: string): void {
  const components = getCustomComponents();
  const filtered = components.filter(c => c.id !== id);
  saveCustomComponents(filtered);
}

/**
 * 生成唯一 ID
 */
export function generateComponentId(): string {
  return `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
